package com.czh.subject.domain.handler.subject;

import com.czh.subject.common.enums.SubjectTypeEnum;
import com.czh.subject.domain.convert.SubjectMultipleConverter;
import com.czh.subject.domain.entity.SubjectAnswerAndOptionBO;
import com.czh.subject.domain.entity.SubjectInfoBO;
import com.czh.subject.domain.entity.SubjectOptionBO;
import com.czh.subject.infra.basic.entity.SubjectMultiple;
import com.czh.subject.infra.basic.service.SubjectMultipleService;
import com.google.common.base.Preconditions;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

/**
 * @author czh01
 * @version 1.0
 * @description: 多选题策略
 * @date 2024/7/31 下午 2:29
 */
@Component
public class MultipleTypeHandler implements SubjectTypeHandler {
    @Resource
    private SubjectMultipleService subjectMultipleService;

    @Override
    public SubjectTypeEnum getHandlerType() {
        return SubjectTypeEnum.MULTIPLE;
    }

    @Override
    public boolean add(SubjectInfoBO subjectInfoBO) {
        try {
            Preconditions.checkNotNull(subjectInfoBO.getOptionList(), "题目答案和选项不能为空!");
            List<SubjectMultiple> subjectMultipleList = new LinkedList<>();
            subjectInfoBO.getOptionList().forEach(option -> {
                SubjectMultiple subjectMultiple = SubjectMultipleConverter.INSTANCE.convert(option);
                subjectMultiple.setSubjectId(subjectInfoBO.getId());
                subjectMultipleList.add(subjectMultiple);
            });
            return subjectMultipleService.saveBatch(subjectMultipleList);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public SubjectAnswerAndOptionBO queryOptionAndAnswer(Long id) {
        SubjectMultiple subjectMultiple = new SubjectMultiple();
        subjectMultiple.setSubjectId(id);
        List<SubjectMultiple> subjectMultipleList = subjectMultipleService.querySubjectMultipleList(subjectMultiple);
        List<SubjectOptionBO> subjectOptionBOList = SubjectMultipleConverter.INSTANCE.convert(subjectMultipleList);
        SubjectAnswerAndOptionBO subjectAnswerAndOptionBO = new SubjectAnswerAndOptionBO();
        subjectAnswerAndOptionBO.setOptionList(subjectOptionBOList);
        return subjectAnswerAndOptionBO;
    }
}
